package com.sunwoda.springbootredis.redislock.impl;

import com.sunwoda.springbootredis.redislock.RedisLock;
import com.sunwoda.springbootredis.util.RedisBean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.concurrent.TimeUnit;

/**
 * @program: springbootredis
 * @description: redis实现分布式锁
 * @author: SGR
 * @create: 2021-09-15 08:46
 **/
public class RedisLockImpl implements RedisLock {

    /**
     * 存在的问题  没有实现加锁解锁一体化，可能存在一个线程只解锁，会将其他线程的锁释放掉
     */

    /**
    * @Description: 加锁
    * @Param:
    * @return:
    * @Author: SGR
    * @Date: 2021-09-15
    */
    @Override
    public boolean tryLock(String key, long timeout, TimeUnit timeUnit) {
        RedisTemplate redis = RedisBean.redis;
        redis.setKeySerializer(new StringRedisSerializer());
        return redis.opsForValue().setIfAbsent(key, "lock", timeout, timeUnit);
    }

    /**
    * @Description: 释放锁
    * @Param:
    * @return:
    * @Author: SGR
    * @Date: 2021-09-15
    */
    @Override
    public void releaseLock(String key) {
        RedisTemplate redisTemplate = RedisBean.redis;
        redisTemplate.delete(key);
    }
}
